package com.lxw.manage.course.service.impl;

import com.alibaba.fastjson.JSON;
import com.lxw.client.CmsPageClient;
import com.lxw.framework.domain.cms.CmsPage;
import com.lxw.framework.domain.cms.response.CmsPageResult;
import com.lxw.framework.domain.course.*;
import com.lxw.framework.domain.course.ext.TeachplanNode;
import com.lxw.framework.domain.course.response.CmsPostPageResult;
import com.lxw.framework.domain.course.response.CoursePublishResult;
import com.lxw.framework.domain.course.response.CourseView;
import com.lxw.framework.exception.CustomException;
import com.lxw.framework.model.response.CommonCode;
import com.lxw.framework.model.response.ResponseResult;
import com.lxw.framework.utils.DateUtils;
import com.lxw.manage.course.dao.*;
import com.lxw.manage.course.service.ICourseMarketService;
import com.lxw.manage.course.service.ICourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class CourseServiceImpl implements ICourseService {
    @Autowired
    TeachplanMapper teachplanMapper;
    @Autowired
    TeachplanRepository teachplanRepository;
    @Autowired
    CourseBaseRepository courseBaseRepository;
    @Autowired
    CoursePicRepository coursePicRepository;
    @Autowired
    CoursePubRepository coursePubRepository;
    @Autowired
    TeachPlanMediaRepository teachPlanMediaRepository;
    @Autowired
    TeachplanMediaPubRepository teachplanMediaPubRepository;
    @Autowired
    ICourseMarketService courseMarketService;
    @Value("${preview.url}")
    private String preView;
    @Autowired
    CmsPageClient cmsPageClient;

    @Override
    public TeachplanNode findTeachplanList(String courseId) {
        // 校验 课程必须存在


        return teachplanMapper.selectList(courseId);
    }

    @Override
    @Transactional
    public ResponseResult addTeachplan(Teachplan teachplan) {
        // 1.先查询根节点
        List<Teachplan> byCourseidAndParentid = teachplanRepository.findByCourseidAndParentid(teachplan.getCourseid(), "0");
        Teachplan rootPlan = null;
        if(byCourseidAndParentid==null||byCourseidAndParentid.size()==0){
            // 添加根节点
            rootPlan = new Teachplan();
            rootPlan.setCourseid(teachplan.getCourseid());
            rootPlan.setParentid("0");
            rootPlan.setOrderby(1);
            rootPlan.setGrade("1");

            Optional<CourseBase> byId = courseBaseRepository.findById(teachplan.getCourseid());
            CourseBase courseBase = byId.get();

            rootPlan.setPname(courseBase.getName());//课程名
            rootPlan.setStatus("0");//状态为必填项
            rootPlan = teachplanRepository.save(rootPlan);
        }else {
            rootPlan =  byCourseidAndParentid.get(0);
        }
        // 2. 是否选择上级节点 如果不选用根节点ID
        if(StringUtils.isEmpty(teachplan.getParentid())){
            teachplan.setParentid(rootPlan.getId());//设置根节点ID  此时属于二级菜单
            teachplan.setGrade("2");
        }else {
            Optional<Teachplan> byId = teachplanRepository.findById(teachplan.getParentid());//获取选择父级节点
            if(!byId.isPresent()){
                throw new CustomException(CommonCode.FAIL);
            }
            Teachplan teachplan1 = byId.get();
            String grade = teachplan1.getGrade();

            teachplan.setGrade(String.valueOf(Integer.parseInt(grade)+1));
        }

        // 3. 保存节点
         teachplanRepository.save(teachplan);



        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    public Teachplan findTeachplanById(String id) {
        Optional<Teachplan> byId = teachplanRepository.findById(id);
        if(byId.isPresent()){
            return byId.get();
        }
        return null;
    }

    @Override
    @Transactional
    public ResponseResult delTeachplan(String id) {
        Teachplan teachplan = this.findTeachplanById(id);
        if(teachplan==null){
            throw new CustomException(CommonCode.FAIL);
        }

        // 判断是2级还是三级
        String grade = teachplan.getGrade();

        if("2".equals(grade)){
            // 删除三级
            teachplanMapper.delByParentid(id);
        }else if("1".equals(grade)){
            // 一级菜单 根据courseID删除

        }
        teachplanRepository.deleteById(id);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    @Transactional
    public ResponseResult addCourse(CourseBase courseBase) {
        courseBaseRepository.save(courseBase);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    public Page<CourseBase> findList(Integer page, Integer pageSize) {
        // 页码从0开始
        page --;

        Pageable pageable = PageRequest.of(page,pageSize);
        Page<CourseBase> all = courseBaseRepository.findAll(pageable);

        return all;
    }

    @Override
    public CourseBase findCoursebaseById(String courseId) {

        Optional<CourseBase> byId = courseBaseRepository.findById(courseId);
        if(byId.isPresent()){
            return byId.get();
        }
        return null;
    }

    @Override
    @Transactional
    public CourseBase editCourse(String courseId, CourseBase courseBase) {
        CourseBase coursebaseById = this.findCoursebaseById(courseId);
        if(coursebaseById==null){
            throw new CustomException(CommonCode.FAIL);
        }

        courseBaseRepository.save(courseBase);
        return courseBase;
    }

    @Override
    public ResponseResult addCoursePic(String courseId, String pic) {
        CoursePic coursePic = new CoursePic();
        coursePic.setCourseid(courseId);
        coursePic.setPic(pic);
        coursePicRepository.save(coursePic);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    public CoursePic findCoursePicById(String courseId) {
        Optional<CoursePic> byId = coursePicRepository.findById(courseId);
        if(byId.isPresent()){
            return byId.get();
        }

        return null;
    }

    @Override
    public ResponseResult delCoursePicById(String courseId) {
        coursePicRepository.deleteById(courseId);

        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    public CourseView getModelData(String courseId) {
        /**
         * 课程基本信息
         */
        CourseView courseView = new CourseView();
        CourseBase courseBase = this.findCoursebaseById(courseId);
        courseView.setCourseBase(courseBase);
        /**
         * 课程图片
         */
        CoursePic coursePic = this.findCoursePicById(courseId);
        courseView.setCoursePic(coursePic);
        /**
         * 课程营销信息
         */
        CourseMarket courseMarketById = courseMarketService.findCourseMarketById(courseId);
        courseView.setCourseMarket(courseMarketById);

        /**
         * 课程计划
         */
        TeachplanNode teachplanList = this.findTeachplanList(courseId);
        courseView.setTeachplanNode(teachplanList);

        return courseView;
    }

    @Value("${coursePublish.siteId}")
    private String siteId;
    @Value("${coursePublish.templateId}")
    private String templateId;
    @Value("${coursePublish.pageWebPath}")
    private String pageWebPath;
    @Value("${coursePublish.pagePhysicalPath}")
    private String pagePhysicalPath;
    @Value("${coursePublish.dataUrlPre}")
    private String dataUrlPre;

    @Override
    public CoursePublishResult preview(String id) {
        CourseBase courseBase = this.findCoursebaseById(id);

        //
        String pageId = null;
        CmsPage cmsPage = new CmsPage();
        cmsPage.setSiteId(siteId);
        cmsPage.setTemplateId(templateId);
        cmsPage.setPageWebPath(pageWebPath);
        cmsPage.setPagePhysicalPath(pagePhysicalPath);
        cmsPage.setDataUrl(dataUrlPre+id);
        cmsPage.setPageCreateTime(new Date());
        cmsPage.setPageType("1");
        cmsPage.setPageName("preview_"+System.currentTimeMillis()+".html");
        cmsPage.setPageAliase(courseBase.getName()+"-课程预览页面");

        // 远程调用保存页面信息
        CmsPageResult cmsPageResult = cmsPageClient.add(cmsPage);
        CmsPage cmsPage1 = cmsPageResult.getCmsPage();
        // 获取保存页面信息的主键ID也就是pageId
        pageId = cmsPage1.getPageId();

        String preViewUrl = preView+pageId; //预览地址

        return new CoursePublishResult(CommonCode.SUCCESS,preViewUrl);
    }

    @Override
    public CoursePublishResult publish(String id) {
        CourseBase courseBase = this.findCoursebaseById(id);

        //
        CmsPage cmsPage = new CmsPage();
        cmsPage.setSiteId(siteId);
        cmsPage.setTemplateId(templateId);
        cmsPage.setPageWebPath(pageWebPath);
        cmsPage.setPagePhysicalPath(pagePhysicalPath);
        cmsPage.setDataUrl(dataUrlPre+id);
        cmsPage.setPageCreateTime(new Date());
        cmsPage.setPageType("1");
        cmsPage.setPageName(id+".html");
        cmsPage.setPageAliase(courseBase.getName());
        CmsPostPageResult cmsPostPageResult = cmsPageClient.postPageQuick(cmsPage);
        if(!cmsPostPageResult.isSuccess()){
            return new CoursePublishResult(CommonCode.FAIL,null);
        }

        // 更新课程为已发布状态
        /**
         * {
         *             "sd_name": "制作中",
         *             "sd_id": "202001",
         *             "sd_status": "1"
         *         },
         *         {
         *             "sd_name": "已发布",
         *             "sd_id": "202002",
         *             "sd_status": "1"
         *         },
         *         {
         *             "sd_name": "已下线",
         *             "sd_id": "202003",
         *             "sd_status": "1"
         *         }
         */
        courseBase.setStatus("202002");//
        courseBaseRepository.save(courseBase);

        // 课程发布数据处理
        createCoursePub(id);
        // 媒体资源信息处理
        this.saveTeachplanMediaPub(id);
        return new CoursePublishResult(CommonCode.SUCCESS,cmsPostPageResult.getPageUrl());
    }

    @Override
    public ResponseResult savemedia(TeachplanMedia teachplanMedia) {
        // 业务处理 TODO  非空校验
        teachPlanMediaRepository.save(teachplanMedia);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    private void createCoursePub(String courseId){
        // 1.准备数据
        CoursePub coursePub =  getCoursePub(courseId);

        // 2.保存或者更新
        coursePubRepository.save(coursePub);
//        Optional<CoursePub> byId = coursePubRepository.findById(courseId);
//        if(byId.isPresent()){
//            // 数据已存在
//            coursePubRepository.save(coursePub);
//        }else {
//
//        }

    }

    private CoursePub getCoursePub(String courseId) {
        CoursePub coursePub = new CoursePub();
        CourseView modelData = this.getModelData(courseId);
        CourseBase courseBase = modelData.getCourseBase();
        CourseMarket courseMarket = modelData.getCourseMarket();
        CoursePic coursePic = modelData.getCoursePic();
        TeachplanNode teachplanNode = modelData.getTeachplanNode();


        coursePub.setCharge(courseMarket.getCharge());
        coursePub.setValid(courseMarket.getValid());
        coursePub.setQq(courseMarket.getQq());
        coursePub.setPrice(courseMarket.getPrice());
        coursePub.setPrice_old(courseMarket.getPrice_old());

        coursePub.setPic(coursePic.getPic());

        coursePub.setDescription(courseBase.getDescription());
        coursePub.setId(courseId);//设置主键为课程ID
        coursePub.setName(courseBase.getName());
        coursePub.setUsers(courseBase.getUsers());
        coursePub.setMt(courseBase.getMt());
        coursePub.setSt(courseBase.getSt());
        coursePub.setGrade(courseBase.getGrade());
        coursePub.setStudymodel(courseBase.getStudymodel());
        coursePub.setTeachmode(courseBase.getTeachmode());

        List<TeachplanNode> children = teachplanNode.getChildren();
//        List<String> list = new ArrayList<>();
//        children.forEach(teachplanNode1 -> {
//            list.add(teachplanNode1.getPname());
//        });

        coursePub.setTeachplan(JSON.toJSONString(children));
        coursePub.setPubTime(DateUtils.formatNow("yyyy-MM-dd HH:mm:ss"));
        coursePub.setTimestamp(new Date());
        return coursePub;
    }
    //保存课程计划媒资信息
    private void saveTeachplanMediaPub(String courseId){
        //查询课程媒资信息
        TeachplanMedia teachplanMedia2 = new TeachplanMedia();
        teachplanMedia2.setCourseId(courseId);
        Example<TeachplanMedia> example = Example.of(teachplanMedia2);
        List<TeachplanMedia> teachplanMediaList = teachPlanMediaRepository.findAll(example);
        //将课程计划媒资信息存储待索引表
//        teachplanMediaPubRepository.deleteByCourseId(courseId);
        List<TeachplanMediaPub> teachplanMediaPubList = new ArrayList<>();
        for(TeachplanMedia teachplanMedia:teachplanMediaList){
            TeachplanMediaPub teachplanMediaPub =new TeachplanMediaPub();
            BeanUtils.copyProperties(teachplanMedia,teachplanMediaPub);
            teachplanMediaPub.setTimestamp(new Date());
            teachplanMediaPubList.add(teachplanMediaPub);
        }
        teachplanMediaPubRepository.saveAll(teachplanMediaPubList);
    }
}
